from flask import Flask, request
from db.data_operate import *
from flasgger import Swagger, swag_from
from flask_cors import CORS
import json

app = Flask(__name__)
app.config['SECRET_KEY'] = 'xqx-milestone'
CORS(app, resources=r'/*')
swagger = Swagger(app)


@app.route('/')
@swag_from('./swagger_yaml/index.yaml')
def hello_world():  # put application's code here
    return 'Hello World!'


@app.route('/login', methods=('POST',))
@swag_from('./swagger_yaml/login.yaml')
def login():
    data = request.get_json()
    code, msg = user_login(data['user-name'], data['user-pwd'])
    json_str = json.dumps({'code': code, 'message': msg})
    return json_str, 200, {"Content-Type": "application/json"}


@app.route('/register', methods=('POST',))
@swag_from('./swagger_yaml/register.yaml')
def register():
    data = request.get_json()
    code, msg = user_register(data['user-name'], data['user-pwd'])
    json_str = json.dumps({'code': code, 'message': msg})
    return json_str, 200, {"Content-Type": "application/json"}

@app.route('/change_pwd', methods=('POST',))
@swag_from('./swagger_yaml/change_pwd.yaml')
def pwdChange():
    data = request.get_json()
    code, msg = user_pwd_change(data['user-name'], data['user-pwd'])
    json_str = json.dumps({'code': code, 'message': msg})
    return json_str, 200, {"Content-Type": "application/json"}

@app.route('/create_project', methods=('POST',))
@swag_from('./swagger_yaml/create_project.yaml')
def new_project():
    data = request.get_json()
    user_id = get_user_id(data['user-name'])
    code, msg = create_project(data['project-name'], user_id)
    json_str = json.dumps({'code': code, 'message': msg})
    return json_str, 200, {"Content-Type": "application/json"}


@app.route('/get_project', methods=('POST',))
@swag_from('./swagger_yaml/get_project.yaml')
def get_project():
    """
    获取所有工程名称及进度
    """
    data = request.get_json()
    user_id = get_user_id(data['user-name'])
    project_name_list = get_user_project(user_id)
    ans = {}
    for i in project_name_list:
        project_id = get_project_id(i, user_id)
        content_list = get_project_progress(project_id)
        ans[i] = content_list
    json_str = json.dumps({'code': 0, 'projects': ans})
    return json_str, 200, {"Content-Type": "application/json"}


@app.route('/add_progress', methods=('POST',))
@swag_from('./swagger_yaml/add_progress.yaml')
def add_progress():
    data = request.get_json()
    user_id = get_user_id(data['user-name'])
    project_id = get_project_id(data['project-name'], user_id)
    code, msg = add_project_progress(project_id, data['today-progress'])
    json_str = json.dumps({'code': code, 'message': msg})
    return json_str, 200, {"Content-Type": "application/json"}


if __name__ == '__main__':
    app.run()
